package com.server.core;

import com.server.runtime.simulationImpl;
import com.server.runtime.scenarioImpl;
import com.server.runtime.chatImpl;

import gnu.cajo.invoke.Remote;
import gnu.cajo.utils.ItemServer;

public class Server {
	private static boolean started = false;

	public static void bootServer() throws Exception {
		try {
			// Configure CAJO remote server
			Remote.config(null, Config.cajoPort, null, 0);
		} catch(Exception e) {
			System.out.println("ERROR: Could not setup the server.");
		}
	}
	
	 public static void startServer() throws Exception {             
         if(isStarted()) {
                 System.out.println("WARNING: Loader is already done, can't load two scenarios into one Simulator.");
         } else {
        	 //Try to startup the server
			try {

				try {
					//Bind the components to the server
					ItemServer.bind(simulationImpl.getReference(), "Simulation");
					ItemServer.bind(scenarioImpl.instance(), "Scenario");
					ItemServer.bind(chatImpl.instance(), "Chat");
					System.out.println("UPDATE: Server is running!");
					System.out.println("UPDATE: Server runs on: " + Config.cajoHost);
                    System.out.println("UPDATE: Running on port: " + Config.cajoPort);
                    System.out.println("______________________________________________\n");
                    started = true;

       			 	Simulator.startSimulator();
       				JConsole.startConsole();
				} catch (Exception e) {
					System.out.println("ERROR: Server already running!");
				}
			} catch (Exception e){
				System.out.println("ERROR Server creation failed...");
			}
         }
	}
	 
	public static void restartServer() throws Exception {
		try {
			System.out.println("UPDATE: Server is restarting, please wait...");
			shutdownServer();
			startServer();
			System.out.println("UPDATE: Server restart successful.");
		} catch (Exception e){
			System.out.println("ERROR: Restarting the server failed...");
		}
	} 
	 
	public static void shutdownServer() throws Exception {
		try {
			started = false;
			Remote.shutdown();
			System.out.println("UPDATE: Server is shutdown.");
		} catch (Exception e){
			System.out.println("ERROR: Server creation failed...");
		}
	}

	private static boolean isStarted() {
		return started;
	}
}
